package cn.bugDance.domain.rebate.service;

import cn.bugDance.domain.rebate.event.RebateEvent;
import cn.bugDance.domain.rebate.model.aggregate.UserBehaviorRebateOrderAggregate;
import cn.bugDance.domain.rebate.model.entity.*;
import cn.bugDance.domain.rebate.model.valobj.BehaviorVO;
import cn.bugDance.domain.rebate.model.valobj.RebateDataVO;
import cn.bugDance.domain.rebate.model.valobj.TaskStateVO;
import cn.bugDance.domain.rebate.repository.IRebateRepository;
import cn.bugDance.types.common.Constants;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.List;

@Service("calendarSignRebateService")
public class CalendarSignRebateService extends AbstractRebateService{

    @Resource
    private IRebateRepository rebateRepository;

    private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void doSaveOrders(UserBehaviorRebateOrderAggregate userBehaviorRebateOrderAggregate, BehaviorEntity behaviorEntity) {
        rebateRepository.saveCalendarSignRebateOrder(userBehaviorRebateOrderAggregate);
    }

    @Override
    protected UserBehaviorRebateOrderAggregate buildUserBehaviorRebateOrderAggregates(List<DallyBehaviorRebateEntity> behaviorRebateEntities, BehaviorEntity behaviorEntity) {

        UserBehaviorRebateOrderAggregate userBehaviorRebateOrderAggregate = new UserBehaviorRebateOrderAggregate();

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        String previousDay = dateFormat.format(calendar.getTime());

        UserCalendarSignRecordEntity userCalendarSignRecordReqEntity = new UserCalendarSignRecordEntity();
        userCalendarSignRecordReqEntity.setUserId(behaviorEntity.getUserId());
        userCalendarSignRecordReqEntity.setActivityId(behaviorEntity.getActivityId());
        userCalendarSignRecordReqEntity.setSignDay(previousDay);
        UserCalendarSignRecordEntity userCalendarSignRecordResEntity = rebateRepository.queryPreviousSignDay(userCalendarSignRecordReqEntity);

        List<CheckInConfigEntity> checkInConfigEntities = rebateRepository.queryCheckInConfig();

        UserCalendarSignRecordEntity userCalendarSignRecordEntity = new UserCalendarSignRecordEntity();
        userCalendarSignRecordEntity.setUserId(behaviorEntity.getUserId());
        userCalendarSignRecordEntity.setSignDay(behaviorEntity.getSignDay());
        userCalendarSignRecordEntity.setSignMonth(behaviorEntity.getSignMonth());
        userCalendarSignRecordEntity.setActivityId(behaviorEntity.getActivityId());
        userCalendarSignRecordEntity.setBizId(behaviorEntity.getUserId() + Constants.UNDERLINE + behaviorEntity.getActivityId() + Constants.UNDERLINE + behaviorEntity.getSignDay());
        userCalendarSignRecordEntity.setIsRebate(0);

        Integer dayOfMonth = dayOfMonth(behaviorEntity.getSignDay());

        if(userCalendarSignRecordResEntity != null){
            userCalendarSignRecordEntity.setLongSignDay(isFirstDayOfMonth(behaviorEntity.getSignDay()) ? 1 : (userCalendarSignRecordResEntity.getLongSignDay() + 1));
            for(CheckInConfigEntity checkInConfigEntity : checkInConfigEntities){
                if((checkInConfigEntity.getLongCheckInDay() * dayOfMonth) == userCalendarSignRecordEntity.getLongSignDay()){
                    userCalendarSignRecordEntity.setIsRebate(1);
                    userCalendarSignRecordEntity.setRebateType(checkInConfigEntity.getRebateType());
                    userCalendarSignRecordEntity.setRebateConfig(checkInConfigEntity.getRebateConfig());
                    break;
                }
            }
        }
        else{
            userCalendarSignRecordEntity.setLongSignDay(1);
            for(CheckInConfigEntity checkInConfigEntity : checkInConfigEntities){
                if((checkInConfigEntity.getLongCheckInDay() * dayOfMonth) == 1){
                    userCalendarSignRecordEntity.setIsRebate(1);
                    userCalendarSignRecordEntity.setRebateType(checkInConfigEntity.getRebateType());
                    userCalendarSignRecordEntity.setRebateConfig(checkInConfigEntity.getRebateConfig());
                    break;
                }
            }
        }

        userBehaviorRebateOrderAggregate.setUserId(behaviorEntity.getUserId());
        userBehaviorRebateOrderAggregate.setUserCalendarSignRecordEntity(userCalendarSignRecordEntity);
        userBehaviorRebateOrderAggregate.setActivityId(behaviorEntity.getActivityId());
        userBehaviorRebateOrderAggregate.setMonth(behaviorEntity.getSignMonth());

        for(DallyBehaviorRebateEntity behaviorRebateEntity : behaviorRebateEntities){

            String bizId = behaviorEntity.getUserId() + Constants.UNDERLINE + behaviorEntity.getActivityId() + Constants.UNDERLINE + behaviorEntity.getSignDay() + Constants.UNDERLINE + behaviorEntity.getBehaviorType() + Constants.UNDERLINE + behaviorRebateEntity.getRebateType();
            UserBehaviorRebateOrderEntity userBehaviorRebateOrderEntity = new UserBehaviorRebateOrderEntity();
            userBehaviorRebateOrderEntity.setOrderId(RandomStringUtils.randomNumeric(12));
            userBehaviorRebateOrderEntity.setUserId(behaviorEntity.getUserId());
            userBehaviorRebateOrderEntity.setBizId(bizId);
            userBehaviorRebateOrderEntity.setBehaviorType(BehaviorVO.valueOf(behaviorEntity.getBehaviorType()));
            userBehaviorRebateOrderEntity.setRebateType(behaviorRebateEntity.getRebateType());
            userBehaviorRebateOrderEntity.setRebateConfig(behaviorRebateEntity.getRebateConfig());
            userBehaviorRebateOrderEntity.setRebateDesc(behaviorRebateEntity.getRebateDesc());

            TaskEntity taskEntity = new TaskEntity();
            taskEntity.setUserId(behaviorEntity.getUserId());
            taskEntity.setTopic(RebateEvent.topic);
            taskEntity.setState(TaskStateVO.NOT_COMPLETED);
            RebateDataVO rebateData = new RebateDataVO();
            rebateData.setBizId(bizId);
            rebateData.setUserId(behaviorEntity.getUserId());
            rebateData.setRebateType(behaviorRebateEntity.getRebateType());
            rebateData.setRebateConfig(behaviorRebateEntity.getRebateConfig());
            taskEntity.setMessage(RebateEvent.create(rebateData));

            userBehaviorRebateOrderAggregate.put(userBehaviorRebateOrderEntity, taskEntity);
        }

        if(userCalendarSignRecordEntity.getIsRebate() == 1){
            String bizId = behaviorEntity.getUserId() + Constants.UNDERLINE + behaviorEntity.getActivityId() + Constants.UNDERLINE + behaviorEntity.getSignDay() + Constants.UNDERLINE + behaviorEntity.getBehaviorType() + Constants.UNDERLINE + userCalendarSignRecordEntity.getRebateType().getCode() + Constants.UNDERLINE + Constants.LONG_SIGN_REBATE;
            UserBehaviorRebateOrderEntity userBehaviorRebateOrderEntity = new UserBehaviorRebateOrderEntity();
            userBehaviorRebateOrderEntity.setUserId(behaviorEntity.getUserId());
            userBehaviorRebateOrderEntity.setBizId(bizId);
            userBehaviorRebateOrderEntity.setOrderId(RandomStringUtils.randomNumeric(12));
            userBehaviorRebateOrderEntity.setBehaviorType(BehaviorVO.valueOf(behaviorEntity.getBehaviorType()));
            userBehaviorRebateOrderEntity.setRebateType(userCalendarSignRecordEntity.getRebateType().getCode());
            userBehaviorRebateOrderEntity.setRebateConfig(userCalendarSignRecordEntity.getRebateConfig());

            TaskEntity taskEntity = new TaskEntity();
            taskEntity.setUserId(behaviorEntity.getUserId());
            taskEntity.setTopic(RebateEvent.topic);
            taskEntity.setState(TaskStateVO.NOT_COMPLETED);
            RebateDataVO rebateData = new RebateDataVO();
            rebateData.setBizId(bizId);
            rebateData.setUserId(behaviorEntity.getUserId());
            rebateData.setRebateType(userBehaviorRebateOrderEntity.getRebateType());
            rebateData.setRebateConfig(userBehaviorRebateOrderEntity.getRebateConfig());
            taskEntity.setMessage(RebateEvent.create(rebateData));

            userBehaviorRebateOrderAggregate.put(userBehaviorRebateOrderEntity, taskEntity);
        }

        return userBehaviorRebateOrderAggregate;
    }

    private boolean isFirstDayOfMonth(String day){
        // 创建一个DateTimeFormatter来解析日期字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse(day, formatter);
        // 获取当月的第一天
        LocalDate firstDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth());
        return date.isEqual(firstDayOfMonth);
    }

    private Integer dayOfMonth(String day){
        // 创建一个DateTimeFormatter来解析日期字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 解析日期字符串
        LocalDate date = LocalDate.parse(day, formatter);
        // 从LocalDate获取YearMonth
        YearMonth yearMonth = YearMonth.from(date);
        return yearMonth.lengthOfMonth();
    }
}
